﻿using System;
using System.Collections.Generic;

using System.Windows;
using System.Windows.Controls;

using System.Windows.Input;
using System.Windows.Navigation;

using System.Windows.Media.Animation;

using System.Threading;
using System.Windows.Threading;

using EagleJournalBE.Util;
using EagleJournalBE.Database.Tables;
using System.ComponentModel;

namespace EagleJournal
{
	public partial class ScreenLogin : UserControl
	{
        public static readonly  RoutedEvent
            InvokeSuccessfulLoginEvent      = EventManager.RegisterRoutedEvent("InvokeSuccessfulLogin", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(ScreenLogin));
        public event            RoutedEventHandler
            InvokeSuccessfulLogin
        {
            add     { this.AddHandler(InvokeSuccessfulLoginEvent, value); }
            remove  { this.RemoveHandler(InvokeSuccessfulLoginEvent, value); }
        }

        public static readonly  RoutedEvent
            InvokeHelpButtonClickedEvent    = EventManager.RegisterRoutedEvent("InvokeHelpButtonClicked", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(ScreenLogin));
        public event RoutedEventHandler
            InvokeHelpButtonClicked
        {
            add     { this.AddHandler(InvokeHelpButtonClickedEvent, value); }
            remove  { this.RemoveHandler(InvokeHelpButtonClickedEvent, value); }
        }

        public static readonly  RoutedEvent
            InvokeExitButtonClickedEvent    = EventManager.RegisterRoutedEvent("InvokeExitButtonClicked", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(ScreenLogin));
        public event RoutedEventHandler
            InvokeExitButtonClicked
        {
            add     { this.AddHandler(InvokeExitButtonClickedEvent, value); }
            remove  { this.RemoveHandler(InvokeExitButtonClickedEvent, value); }
        }

        DispatcherTimer loginCheckDelay     = new DispatcherTimer();

        Storyboard      showForgot;
        Storyboard      hideForgot;

        TableUserType   userTypes;

		public                  ScreenLogin                         ()
		{
            this.InitializeComponent();

            try
            {
                if (!DesignerProperties.GetIsInDesignMode(this))
                {
                    this.userTypes = new TableUserType();
                    this.userTypes.Refresh();
                }
            }
            catch (Exception)
            {
                Logger.WriteInfo(LoggingType.WARN, this, "MySQL connector is in an invalid state! This should not happen normally.");
            }

            loginCheckDelay.Interval = new TimeSpan(0, 0, 1);
            loginCheckDelay.Tick += new EventHandler((o, e) =>
            {
                bool isVerified = false;

                // check database for password here
                foreach (List<object> row in this.userTypes.TableData)
                {
                    if ((int)row[0] == (this.ComboUser.SelectedIndex + 1001))
                        if ((string)row[1] == this.TextPassword.Password)
                            isVerified = true;
                }

                if (isVerified)
                {
                    this.RaiseEvent(new RoutedEventArgs(InvokeSuccessfulLoginEvent));
                }
                else
                {
                    VisualStateManager.GoToState(this, "ToError", true);

                    FocusHelper.Focus(this.ButtonRetry);
                }
                loginCheckDelay.Stop();
            });
		}

        public override void    OnApplyTemplate                     ()
        {
            base.OnApplyTemplate();

            showForgot = (Storyboard)this.FindResource("ShowForgot");
            hideForgot = (Storyboard)this.FindResource("HideForgot");
            hideForgot.Completed += new EventHandler((o, sbe) =>
            {
                this.RootGrid.Children.Remove(this.PasswordOption);
            });

            showForgot.Freeze();
            hideForgot.Freeze();
        }

        private         void    UserControl_Loaded                  (object sender, RoutedEventArgs e)
        {
            this.RootGrid.Children.Remove(this.PasswordOption);
        }

        private         void    ButtonLogin_Click                   (object sender, RoutedEventArgs e)
        {
            VisualStateManager.GoToState(this, "ToVerify", true);

            this.DoLogin();
        }
        private         void    ButtonRetry_Click                   (object sender, RoutedEventArgs e)
        {
            VisualStateManager.GoToState(this, "ToDefault", true);
        }

        private         void    ButtonForgot_Click                  (object sender, RoutedEventArgs e)
        {
            if (!this.RootGrid.Children.Contains(this.PasswordOption))
                this.RootGrid.Children.Add(this.PasswordOption);

            this.PasswordOption.userType = (this.ComboUser.SelectedIndex + 1001);

            this.BeginStoryboard(showForgot);
        }

        private         void    ButtonHelp_Click                    (object sender, RoutedEventArgs e)
        {
            this.RaiseEvent(new RoutedEventArgs(InvokeHelpButtonClickedEvent));
        }
        private         void    ButtonExit_Click                    (object sender, RoutedEventArgs e)
        {
            this.RaiseEvent(new RoutedEventArgs(InvokeExitButtonClickedEvent));
        }

        private         void    UserControl_IsVisibleChanged        (object sender, DependencyPropertyChangedEventArgs e)
        {
            if (this.Visibility == Visibility.Visible)
            {
                VisualStateManager.GoToState(this, "ToDefault", false);

                this.TextPassword.Password = string.Empty;
                FocusHelper.Focus(this.TextPassword);
            }
        }

        private         void    PasswordOption_InvokeDialogClose    (object sender, RoutedEventArgs e)
        {
            this.BeginStoryboard(hideForgot);

            this.userTypes.Refresh();
        }

        public          void    DoLogin                             ()
        {
            if (this.TextPassword.Password.Length > 0)
                loginCheckDelay.Start();
            else
                VisualStateManager.GoToState(this, "ToError", true);
        }
	}
}